package commands

import (
	"context"
	"fmt"

	"github.com/spf13/cobra"
	"github.com/yourusername/virt-manager-go/internal/models"
)

// NewConnectionCommand 创建连接管理命令
func NewConnectionCommand() *cobra.Command {
	cmd := &cobra.Command{
		Use:     "connection",
		Short:   "连接管理",
		Long:    "管理 libvirt 连接",
		Aliases: []string{"conn", "c"},
	}

	cmd.AddCommand(newConnectionListCommand())
	cmd.AddCommand(newConnectionGetCommand())
	cmd.AddCommand(newConnectionAddCommand())
	cmd.AddCommand(newConnectionRemoveCommand())
	cmd.AddCommand(newConnectionDefaultCommand())
	cmd.AddCommand(newConnectionInfoCommand())
	cmd.AddCommand(newConnectionCapabilitiesCommand())
	cmd.AddCommand(newConnectionReconnectCommand())
	cmd.AddCommand(newConnectionCloseCommand())
	cmd.AddCommand(newConnectionReconnectAllCommand())
	cmd.AddCommand(newConnectionHealthCheckCommand())

	return cmd
}

func newConnectionListCommand() *cobra.Command {
	var outputFormat string

	cmd := &cobra.Command{
		Use:     "list",
		Short:   "列出所有连接",
		Aliases: []string{"ls"},
		RunE: func(cmd *cobra.Command, args []string) error {
			client := ClientManager.GetClient(cmd.Flag("server").Value.String())
			connections, err := client.Connection().ListConnections(context.Background())
			if err != nil {
				return fmt.Errorf("列出连接失败: %w", err)
			}

			return printOutput(connections, outputFormat)
		},
	}

	cmd.Flags().StringVarP(&outputFormat, "output", "o", "table", "输出格式 (table, json, yaml)")
	return cmd
}

func newConnectionGetCommand() *cobra.Command {
	var outputFormat string

	cmd := &cobra.Command{
		Use:   "get [name]",
		Short: "获取连接详情",
		Args:  cobra.ExactArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			client := ClientManager.GetClient(cmd.Flag("server").Value.String())
			connection, err := client.Connection().GetConnection(context.Background(), args[0])
			if err != nil {
				return fmt.Errorf("获取连接详情失败: %w", err)
			}

			return printOutput(connection, outputFormat)
		},
	}

	cmd.Flags().StringVarP(&outputFormat, "output", "o", "table", "输出格式 (table, json, yaml)")
	return cmd
}

func newConnectionAddCommand() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "add [name] [uri]",
		Short: "添加新连接",
		Args:  cobra.ExactArgs(2),
		RunE: func(cmd *cobra.Command, args []string) error {
			client := ClientManager.GetClient(cmd.Flag("server").Value.String())
			req := &models.CreateConnectionRequest{
				Name: args[0],
				URI:  args[1],
			}

			err := client.Connection().CreateConnection(context.Background(), req)
			if err != nil {
				return fmt.Errorf("添加连接失败: %w", err)
			}

			fmt.Printf("✅ 连接 %s 添加成功\n", args[0])
			return nil
		},
	}

	return cmd
}

func newConnectionRemoveCommand() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "remove [name]",
		Short: "删除连接",
		Args:  cobra.ExactArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			client := ClientManager.GetClient(cmd.Flag("server").Value.String())
			err := client.Connection().DeleteConnection(context.Background(), args[0])
			if err != nil {
				return fmt.Errorf("删除连接失败: %w", err)
			}

			fmt.Printf("✅ 连接 %s 删除成功\n", args[0])
			return nil
		},
	}

	return cmd
}

func newConnectionDefaultCommand() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "default [name]",
		Short: "设置默认连接",
		Args:  cobra.ExactArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			client := ClientManager.GetClient(cmd.Flag("server").Value.String())
			err := client.Connection().SetDefaultConnection(context.Background(), args[0])
			if err != nil {
				return fmt.Errorf("设置默认连接失败: %w", err)
			}

			fmt.Printf("✅ 连接 %s 设置为默认连接\n", args[0])
			return nil
		},
	}

	return cmd
}

func newConnectionInfoCommand() *cobra.Command {
	var outputFormat string

	cmd := &cobra.Command{
		Use:   "info [name]",
		Short: "获取连接信息",
		Args:  cobra.ExactArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			client := ClientManager.GetClient(cmd.Flag("server").Value.String())
			connection, err := client.Connection().GetConnectionInfo(context.Background(), args[0])
			if err != nil {
				return fmt.Errorf("获取连接信息失败: %w", err)
			}

			return printOutput(connection, outputFormat)
		},
	}

	cmd.Flags().StringVarP(&outputFormat, "output", "o", "table", "输出格式 (table, json, yaml)")
	return cmd
}

func newConnectionCapabilitiesCommand() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "capabilities [name]",
		Short: "获取连接功能信息",
		Args:  cobra.ExactArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			client := ClientManager.GetClient(cmd.Flag("server").Value.String())
			capabilities, err := client.Connection().GetConnectionCapabilities(context.Background(), args[0])
			if err != nil {
				return fmt.Errorf("获取连接功能信息失败: %w", err)
			}

			fmt.Println(capabilities)
			return nil
		},
	}

	return cmd
}

func newConnectionReconnectCommand() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "reconnect [name]",
		Short: "重连连接",
		Args:  cobra.ExactArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			client := ClientManager.GetClient(cmd.Flag("server").Value.String())
			err := client.Connection().ReconnectConnection(context.Background(), args[0])
			if err != nil {
				return fmt.Errorf("重连连接失败: %w", err)
			}

			fmt.Printf("✅ 连接 %s 重连成功\n", args[0])
			return nil
		},
	}

	return cmd
}

func newConnectionCloseCommand() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "close [name]",
		Short: "关闭连接",
		Args:  cobra.ExactArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			client := ClientManager.GetClient(cmd.Flag("server").Value.String())
			err := client.Connection().CloseConnection(context.Background(), args[0])
			if err != nil {
				return fmt.Errorf("关闭连接失败: %w", err)
			}

			fmt.Printf("✅ 连接 %s 关闭成功\n", args[0])
			return nil
		},
	}

	return cmd
}

func newConnectionReconnectAllCommand() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "reconnect-all",
		Short: "重连所有连接",
		RunE: func(cmd *cobra.Command, args []string) error {
			client := ClientManager.GetClient(cmd.Flag("server").Value.String())
			err := client.Connection().ReconnectAll(context.Background())
			if err != nil {
				return fmt.Errorf("重连所有连接失败: %w", err)
			}

			fmt.Println("✅ 所有连接重连成功")
			return nil
		},
	}

	return cmd
}

func newConnectionHealthCheckCommand() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "health [name]",
		Short: "连接健康检查",
		Args:  cobra.ExactArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			client := ClientManager.GetClient(cmd.Flag("server").Value.String())
			err := client.Connection().HealthCheck(context.Background(), args[0])
			if err != nil {
				return fmt.Errorf("连接健康检查失败: %w", err)
			}

			fmt.Printf("✅ 连接 %s 健康检查通过\n", args[0])
			return nil
		},
	}

	return cmd
}
